package cn.jhz.learn.blog.test.impl;

import cn.jhz.learn.blog.component.RequestHolder;
import cn.jhz.learn.blog.service.core.open.EssayService;
import cn.jhz.learn.blog.dao.essay.BlogEssayMapper;
import cn.jhz.learn.blog.po.essay.BlogEssay;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Optional;

@Validated
@Service("essayService")
public class EssayServiceImpl  implements EssayService {

	private final BlogEssayMapper essayMapper;

//	@Autowired
	public EssayServiceImpl(BlogEssayMapper essayMapper) {
		this.essayMapper = essayMapper;
	}

	@Override
	public Optional<BlogEssay> publishEssay(@NotNull @Valid BlogEssay newEssay) {
		//TODO: 内容异常检查
		if(newEssay.getVisibility().equals((byte) 1))
			checkContent(newEssay);
		newEssay.setStatus((byte) 1);
		essayMapper.insertSelective(newEssay);
		return Optional.of(newEssay);
	}

	@Override
	public Optional<Integer> removeEssayById(Integer essayId) {
		checkExist(essayId);
		essayMapper.updateStatusByPrimaryKey(essayId, (byte) 0);
		return Optional.of(essayId);
	}

	@Override
	public Optional<BlogEssay> modifyEssay(@NotNull @Valid BlogEssay essay) {
		checkExist(essay);
		if(essay.getVisibility().equals((byte) 1))
			checkContent(essay);
		essayMapper.updateByPrimaryKeySelective(essay);
		return Optional.of(essay);
	}

	@Override
	public Optional<BlogEssay> findEssayById(@NotNull Integer essayId) {
		return Optional.empty();
	}

	private void checkContent(BlogEssay essay){
		//TODO:内容审查
	}

	@Override
	public void checkExist(Integer essayId){
		BlogEssay essay = essayMapper.selectByPrimaryKey(essayId);
		if(essay == null)
			throw ExceptionConstant.paramEssayIsNotExist.get();
		else if(!essay.getBlogId().equals(RequestHolder.getCurrentUser().getId()))
			throw ExceptionConstant.paramEssayIsNotExist.get();
	}
	private void checkExist(BlogEssay essay){
		checkExist(essay.getId());
	}
}
